<?php
namespace App\Utility;

use Illuminate\Http\Request;

class Upload
{
    /**
     * 上传
     */

    protected static $uploadSizeLimit = 10 * 1024 * 1023; //限制上传尺寸10M

    /**
     * 文件上传
     */
    public static function uploadFile($file)
    {
        $fileSize = $file->getClientSize(); //文件大小
        if(!$file) {
            return array('code'=>'-1', 'msg'=>'文件不存在');
        }
        if ($fileSize > self::$uploadSizeLimit) {
            return array('code'=>'-3', 'msg'=>'文件过大');
        }
        $extension = $file->getClientOriginalExtension(); //获取后缀
        $folderName = 'uploads/'.date('Ymd',time()).'/';
        $safeName = date('YmdHis',time()).rand(10,100).'.'.$extension;
        $file->move($folderName, $safeName);
        $filePath = '/'.$folderName.$safeName;
        $dataArr = array(
            'filePath' => $filePath,
        );
        return array('code'=>'0', 'msg'=>'上传成功', 'data'=>$dataArr);
    }

    /**
     * APP文件上传
     * @return string
     */
    public static function uploadAppFile($files)
    {
        //判断图片存在
        if($files['error']){ return ''; } //错误信息
        if ($files['size'] > self::$uploadSizeLimit) {
            echo "<script>alert('文件过大！');history.go(-1);</script>";exit;
        }
        if(!$files['name']){ return ""; } //文件名称
        //获取文件扩展名
        $temps = explode(".", $files["name"]);
        $extension = end($temps);
        //上传后需要存储的地址
        $folderName = 'uploads/'.date('Ymd',time()).'/';
        if (!is_dir($folderName)) {
            //true表示能创建多级目录，iconv防止中文目录乱码
            mkdir($folderName, 0777, true);
        }
        //上传后的新文件名
        $safeName = date('YmdHis',time()).rand(10,100).'.'.$extension;
        //上传后的地址+文件名
        $filePath = $folderName.$safeName;
        //上传的临时地址
        $tmpName = $files['tmp_name'];
        move_uploaded_file($tmpName, $filePath);
        return '/'.$filePath;
    }
}